﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPWeb.Class;
using KPWeb.Data;
using KPWeb.Function;
using MSExcel = Microsoft.Office.Interop.Excel;



namespace KPWeb.ListyObecnosci
{

    public partial class WyswietExcel : KPPage
    {
        private readonly string[] MonthNames = { "Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień" };
        private short RokPlany
        {

            get
            {
                if (ViewState["RokPlany"] == null)
                    ViewState["RokPlany"] = DateTime.Now.Year;
                return short.Parse(ViewState["RokPlany"].ToString());
            }
            set
            {
                ViewState["RokPlany"] = value;

            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Error1.Visible = false;
            fError.Visible = false;
            if (!IsPostBack)
            {

                dGrupa.Items.Clear();
                dGrupa.Items.Add(new ListItem() { Text = Stale.wybierzGrupe, Value = "0" });
                foreach (vKP_JednostkiGrupy item in Model.GetGrupyDlaFirmy(int.Parse(Current.FirmaID)))
                {
                    dGrupa.Items.Add(new ListItem()
                    {
                        Text = item.GrupaOpis + " (" + item.GrupaID.ToString() + ")",
                        Value = item.GrupaID.ToString()
                    });
                }


                //RokPlany = short.Parse(Request["value"]);
                //RokPlany += short.Parse(DateTime.Now.Year.ToString());


                dYear.Items.Clear();
                foreach (short item in Kalendarz.GetYearGdzieWpisanoSwieta())
                {
                    this.dYear.Items.Add(item.ToString());
                }

                dYear.SelectedValue = RokPlany.ToString();

                //string[] MonthNames
                dMonth.Items.Clear();
                for (int i = 0; i < 12; i++)
                {
                    dMonth.Items.Add(new ListItem()
                     {
                         Text = MonthNames[i],
                         Value = (i + 1).ToString()
                     });

                    //   this.dMonth.Items.Add(MonthNames[i]);
                }

                dYear.SelectedValue = RokPlany.ToString();
                dMonth.SelectedValue = DateTime.Now.Month.ToString();
            }

        }
        protected int ListaObecnosciWyswietlExcel(byte typ, string grupa, int year, int month) //0 bez tytułów, 1 ztytułami
        // 0 OK
        {
            int dlObecnosci = 36;
            int liczbaPozycjiNaStronie = 10;
            int iAll = 0;
            int[][] formatRow = new int[3][];
            formatRow[0] = new int[2] { 1, 12 };
            formatRow[1] = new int[2] { 4, 125 };
            formatRow[2] = new int[2] { 5, 10};
     
            //   string temp = "";
            vKP_Swieta[] ListaSwiat = Kalendarz.GetSwieta(year, month);

            int lastDayMonth = FunctionGlobal.IleDniMiesiac(year, month);


            MSExcel.Application excelApp = new MSExcel.Application();
            string filePath = Server.MapPath("~/EXCEL/SzObecnosci.xls");


            //int[] intArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            //Range rng = excelApp.get_Range("A1", "J1");
            //rng.Value = intArray;

            //nowy otwórz
            //  MSExcel.Workbook newWorkbook = excelApp.Workbooks.Add();
            //istniejacy otwórz
            MSExcel.Workbook excelWorkbook = excelApp.Workbooks.Open(filePath,
                    0, true, 5, "", "", false, MSExcel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);

            //Opis parametrów funkcji   //msdn.microsoft.com/en-us/library/bb179167%28v=office.12%29.aspx
            //  WorkBooks.open(string Filename, object UpdateLinks, object ReadOnly, object Format, object Password,
            //object WriteResPassword, object ReadOnlyRecommend, object Origin, object Delimiter,
            //object Editable, object Notify, object Converter, object AddToMru, object Local, object CorruptLoad )

            MSExcel.Sheets excelSheets = excelWorkbook.Worksheets;

            string currentSheet = "Obecnosci";
            MSExcel.Worksheet excelWorksheet = (MSExcel.Worksheet)excelSheets.get_Item(currentSheet);

            MSExcel.Range excelCell = (MSExcel.Range)excelWorksheet.get_Range("F2", "F2");
            MSExcel.Range excelCellTarget;

            vKP_JednostkiFirmy item1 = Model.GetJednostkaFirma(int.Parse(KPPage.Current.JednostkaID));
            excelCell.Value = item1.JednostkaNazwa;

            excelCell = (MSExcel.Range)excelWorksheet.get_Range("F3", "F3");
            excelCell.Value = MonthNames[month - 1] + " / " + year.ToString();

            DateTime d = new DateTime();
            for (int i = 0; i < lastDayMonth; i++)
            {
                d = new DateTime(year, month, i + 1);
                if (d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday)
                {
                    excelCell = (MSExcel.Range)excelWorksheet.get_Range("C" + (i + 6).ToString(), "L" + (i + 6).ToString());

                    excelCell.Borders.LineStyle = MSExcel.XlLineStyle.xlContinuous;
                    excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalUp].LineStyle = MSExcel.XlLineStyle.xlContinuous;
                }
            }

            foreach (vKP_Swieta sw in ListaSwiat)
            {
                excelCell = (MSExcel.Range)excelWorksheet.get_Range("C" + (sw.day + 5).ToString(), "L" + (sw.day + 5).ToString());

                excelCell.Borders.LineStyle = MSExcel.XlLineStyle.xlContinuous;
                excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalUp].LineStyle = MSExcel.XlLineStyle.xlContinuous;
            }
            for (int i = lastDayMonth; i < 31; i++)
            {
                //   d = new DateTime(year, month, i + 1);

                excelCell = (MSExcel.Range)excelWorksheet.get_Range("C" + (i + 6).ToString(), "L" + (i + 6).ToString());

                excelCell.Borders.LineStyle = MSExcel.XlLineStyle.xlContinuous;
                excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalUp].LineStyle = MSExcel.XlLineStyle.xlContinuous;

            }
         


            int MaxNrStrony = Model.GetListaObecnosciMaxStrona( int.Parse(Current.JednostkaID)) - 1;
            for (int i1 = 0; i1 < MaxNrStrony; i1++)
            {


                iAll += dlObecnosci;
                excelCell = (MSExcel.Range)excelWorksheet.get_Range("A1", "L" + (dlObecnosci).ToString());
                excelCellTarget = (MSExcel.Range)excelWorksheet.get_Range("A" + (iAll +1).ToString(), "L" + (iAll + dlObecnosci).ToString());
              

                //  excelCell.Copy(Type.Missing);
                //  excelCellTarget.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteFormulas,
                //      Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);

                excelCell.Copy(excelCellTarget);
                excelCellTarget.Rows.RowHeight = 19.5;
                for (int i = 0; i < formatRow.Length; i++)
                {
                    ((MSExcel.Range)excelWorksheet.Rows[iAll + formatRow[i][0], Missing.Value]).RowHeight = formatRow[i][1];

                }
                excelCell = (MSExcel.Range)excelWorksheet.get_Range("A" + ((i1 + 1) * dlObecnosci + 1).ToString(), "A" + ((i1 + 1) * dlObecnosci + 1).ToString());
                excelCell.PageBreak = 1;

                excelCell = (MSExcel.Range)excelWorksheet.get_Range("B4", Type.Missing);

            }

            Model model = new Model();
            //  IEnumerable< vKP_OsobyListaObecnosci> ListaObecnosci = this.mo


            int iTemp = 0;
            foreach (vKP_OsobyListaObecnosci item in model.GetListaObecnosci( int.Parse(Current.JednostkaID), int.Parse(grupa)))
            {
                if (typ != 2)
                {
                    if (item.PozycjaNaStronie != null)
                        excelCell.Offset[dlObecnosci * (item.NumerStrony - 1), item.PozycjaNaStronie].Value =
                            (typ == 1 ? item.Tytul.ToLower() : "") + "\r\n" + FunctionGlobal.UppercaseFirstWords(item.NazwiskoImie);
                    //    excelCell.Offset[dlObecnosci * (item.NumerStrony-1 )+1, item.PozycjaNaStronie].Value = iTemp.ToString();
                }
                iTemp += 1;
                //  excelCell.Value = "DDDDDD";
            }

            int l = 0;
            for (int i = 0; i < iTemp; i++)
            {
                for (int j = 0; j < liczbaPozycjiNaStronie && l < iTemp; j++)
                    if (excelCell.Offset[dlObecnosci * (i), j + 1].Value != null)
                    {
                        l += 1;
                        excelCell.Offset[dlObecnosci * (i) + 1, j + 1].Value = l.ToString();

                    }
            }



            excelApp.Visible = true;
            return 0;
        }




        protected void ListaObecnosciView_Click(object sender, System.EventArgs e)
        {
            if (dGrupa.SelectedItem.ToString() == Stale.wybierzGrupe)
            {
                Error1.Visible = true;
                fError.Visible = true;
                return;
            }
            int iTemp = ListaObecnosciWyswietlExcel(0, dGrupa.SelectedValue, int.Parse(dYear.SelectedValue), int.Parse(dMonth.SelectedValue));
        }
        protected void ListaObecnosciViewTytul_Click(object sender, System.EventArgs e)
        {
            if (dGrupa.SelectedItem.ToString() == Stale.wybierzGrupe)
            {
                Error1.Visible = true;
                fError.Visible = true;
                return;
            }
            int iTemp = ListaObecnosciWyswietlExcel(1, dGrupa.SelectedValue, int.Parse(dYear.SelectedValue), int.Parse(dMonth.SelectedValue));
        }

        protected void ListaObecnosciBezNazwisk_Click(object sender, System.EventArgs e)
        {

            int iTemp = ListaObecnosciWyswietlExcel(2, dGrupa.SelectedValue, int.Parse(dYear.SelectedValue), int.Parse(dMonth.SelectedValue));
        }
    }
}